package com.briup.corejava.day16;

/**
 * 多个窗口售票的线程安全问题
 */
public class Test2 {
    public static void main(String[] args) {
        Runnable ticketTask = new TicketTask();
        // 创建三个窗口
        Thread t1 = new Thread(ticketTask,"1号窗口");
        Thread t2 = new Thread(ticketTask,"2号窗口");
        Thread t3 = new Thread(ticketTask,"3号窗口");
        // 启动
        t1.start();
        t2.start();
        t3.start();
    }
}
class TicketTask implements Runnable{
    // 准备任务所需的总票数
    private int num = 50;

    // 锁对象必须是引用类型
    Object obj = new Object();

    @Override
    public void run() {
        // 加锁
        while(true) {
            synchronized (obj) {
                if (num <= 0) {
                    break;
                }
                String name = Thread.currentThread().getName();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " 正在售卖编号为【" + num + "】的票");
                num--;
            }
        }
    }
}
